package org.kisekiproject.instance {
	import flash.utils.Dictionary;
	import flash.utils.describeType;

	/**
	 * @author mikael
	 */
	public class InstanceDefinition {

		private var _class : Class;
		private var _fullName : String;
		private var _shortName : String;
		private var _propertiesByName:Dictionary;

		/**
		 * Constructor.
		 */
		public function InstanceDefinition(cls:Class) {
			_class=cls;
			_propertiesByName=new Dictionary();

			var desc:XML=describeType(cls);

			//trace(desc);
			_fullName=String(desc.@name);
			_shortName=_fullName.substr(_fullName.lastIndexOf(":")+1);

			for each (var accessor:XML in desc..factory..accessor)
				parseProperty(accessor);

			for each (var variable:XML in desc..factory..variable)
				parseProperty(variable);
		}

		/**
		 * Parse a possible property definition.
		 */
		private function parseProperty(accessor:XML):void {
			for each (var metadata:XML in accessor.metadata) {
				if (metadata.@name=="Property") {
					var arrayType:String="String";

					for each (var arg:XML in metadata.arg) {
						if (arg.@key=="arrayType")
							arrayType=arg.@value;
					}

					var prop:PropertyDefinition=new PropertyDefinition(accessor.@name,accessor.@type/*,arrayType*/);

					_propertiesByName[prop.name]=prop;
				}
			}
		}

		/**
		 * Create instance.
		 */
/*		public function createInstance():Instance {
			var object:Object=new _class;

			return new Instance(this, object);
		}*/

		/**
		 * Get class to instantiate.
		 */
		public function get instanceClass():Class {
			return _class;
		}

		/**
		 * Get full name.
		 */
		public function get fullName():String {
			return _fullName;
		}

		/**
		 * Get short name.
		 */
		public function get shortName():String {
			return _shortName;
		}


		/**
		 * Get property definitions.
		 */
		public function getPropertyDefinitionByName(name:String):PropertyDefinition {
			var propDef:PropertyDefinition=_propertiesByName[name];

			//trace("getting prop def: "+name+" its: "+propDef);
			return propDef;
		}

		/**
		 * To string.
		 */
		public function toString():String {
			return "[InstanceDefinition "+_fullName+"]";
		}
	}
}
